package com.simba.server.jsonservice.serivces;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.google.gson.Gson;
import com.simba.common.jsonserver.JsonChannelManager;
import com.simba.server.ServerParam;
import com.simba.server.base.CommonUtil;
import com.simba.server.base.TimeUtil;
import com.simba.server.components.MachineParams;
import com.simba.server.components.data.ResultInfo;
import com.simba.server.webservice.WebServiceManager;
import org.apache.log4j.Logger;
import org.jboss.netty.channel.Channel;
import org.json.JSONObject;


import com.simba.common.jsonservice.JsonService;
import com.simba.common.log.LogUtil;

import com.simba.server.components.SortCommonDefines;

/**
 * Created by kavin on 16-3-30.
 */
public class SortJsonService implements JsonService
{
	public static final String NAME = "MailSortInfo";
	private final static Logger logger = Logger.getLogger(SortJsonService.class);

	@Override
	public void handleRequest(Channel channel, Object content)
	{
		Map<String, Object> sortInfoMap = new HashMap<>();
		sortInfoMap.put(SortCommonDefines.JSON_SERVICE_NAME, "MailSortInfo");
		try
		{
			JSONObject request = (JSONObject) content;
			String barcode = request.getString("barcode");

			String remoteMethod = "chute/retrieve-chute-by-box";

			Map<String,String> rp = new HashMap<>();
			rp.put("guid", CommonUtil.getRandom(1000000000L));
			rp.put("barcode", barcode);
			rp.put("machineCode", MachineParams.getInstance().getDeviceId());

			Gson gson = CommonUtil.getGson();
			String sb = gson.toJson(rp);

			ResultInfo response = WebServiceManager.getInstance().doHttpServiceByPost(ServerParam.REMOTE_WEBSERVICE_ADDRESS, remoteMethod, sb);

			sortInfoMap.put("result", true);
			sortInfoMap.put("response", response);
		}
		catch (Exception ex)
		{
			sortInfoMap.put("result", false);
			sortInfoMap.put("response", "error:"+ex.getMessage());
			LogUtil.LogError(SortJsonService.logger, "Sort Json Service Error " + ex.getMessage());
		}

		JSONObject jsonObject = new JSONObject(sortInfoMap);
		JsonChannelManager.getInstance().commitResponse(channel, jsonObject.toString().getBytes(), false);

	}
}
